
package org.sopt.dev.ImgKnight.agent.NIO;

import org.apache.log4j.Logger;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.Delimiters;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

import org.sopt.dev.ImgKnight.agent.Agent;
import org.sopt.dev.ImgKnight.agent.Controller.TelnetController;

@ChannelPipelineCoverage("all")
public class NioTelnetStreamHandler extends SimpleChannelHandler {

	private Agent agent = null;
	
	private TelnetController telnetController = null;
	
	private Logger exceptionLogger = null;
	
	public NioTelnetStreamHandler() {
		agent = Agent.getInstance();
		telnetController = agent.getTelnetController();
		exceptionLogger = Logger.getLogger("agent.exception");
	}
	
	@Override
	public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {
		e.getChannel().getPipeline().addFirst("encoder", new StringEncoder());
		e.getChannel().getPipeline().addFirst("decoder", new StringDecoder());
		e.getChannel().getPipeline().addFirst("framer", 
				new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
	}
	
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
		telnetController.onConnectionEstablished(e.getChannel()); 
	}
	
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
		telnetController.onRecvedObject(e.getChannel(), e.getMessage());
	}
	
	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
		telnetController.onConnectionClosed(e.getChannel());
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		exceptionLogger.warn("Unexpected exception: " + e.getCause());
	}
}
